<template>
  <div style="width:100%;overflow:hidden">
    <div class="header-top-box" id="header_h" v-if="isShowImg">
      <i class="el-icon-close" @click="changeShowImg"></i>
      <img src="../../../public/img/header_img.png" alt />
    </div>
    <div class="report-box flex" :style="{ height: boxh - headerH + 'px' }">
      <div class="flex" id="father">
        <!-- 时间轴 -->
        <div class="time-box" v-if="reportIndex != 1">
          <el-timeline>
            <el-timeline-item
              v-for="(item, i) in timeList"
              :key="i"
              :class="item.id ? '' : 'year'"
            >
              <span
                v-if="item.id"
                :class="activeIndex == i ? 'month-style active' : 'month-style'"
                @click="() => changeMonth(item, i)"
                >{{ item.cnTimestamp + '月' }}</span
              >
              <span v-else class="year-style">{{ item.timestamp }}年</span>
            </el-timeline-item>
          </el-timeline>
        </div>
        <!-- 报告列表 -->
        <div
          class="report-list-box"
          :style="{ height: boxh - 30 - headerH + 'px' }"
        >
          <div
            class="report-list"
            id="box"
            :style="{ width: isCollapse ? 0 : leftListWidth + 'px' }"
          >
            <div
              class="report-tit"
              v-show="$route.path == '/home/historyPage'"
            ></div>
            <el-collapse
              v-model="activeName"
              accordion
              @change="changeCollapse"
            >
              <template v-for="(item, i) in oneLevelList">
                <el-collapse-item :name="i" :key="i">
                  <template slot="title">
                    <div class="report-collapse-tit">
                      <span>
                        {{ item.name }}
                      </span>
                    </div>
                  </template>
                  <div class="tree-box-content">
                    <el-tree
                      :style="{
                        height:
                          boxh -
                          30 -
                          headerH -
                          oneLevelList.length * 31 -
                          ($route.path == '/home/historyPage' ? 40 : 0) +
                          'px',
                        overflowY: 'auto',
                        overflowX: 'hidden'
                      }"
                      v-if="showReportTree"
                      :data="treeData"
                      :props="defaultProps"
                      @node-click="handleNodeClick"
                      node-key="id"
                      ref="reportTree"
                      :expand-on-click-node="false"
                      :default-expand-all="true"
                      style="width: 100%"
                    >
                      <span
                        class="custom-tree-node"
                        slot-scope="{ node, data }"
                      >
                        <i
                          v-if="data.detailType == 11"
                          class="el-icon-view icon-view-style"
                        ></i>
                        <span>{{ node.label }}</span>
                      </span>
                    </el-tree>
                  </div>
                </el-collapse-item>
              </template>
            </el-collapse>
          </div>

          <!-- 拖动灰块 -->
          <div class="grey-box" v-show="isMove"></div>

          <!-- 收缩栏 -->
          <div
            class="contraction-bar"
            id="scale"
            :style="
              `
              left: ${leftListWidth - parseInt(contractionBarWidth / 2)}px;
              width: ${contractionBarWidth}px
            `
            "
            @mousedown.stop="mouseDownSc"
          ></div>

          <!-- 侧边 收缩栏 -->
          <div
            v-show="!showRightBtn"
            class="show-menu-btn show-left"
            @click="showRightBtnFun"
          >
            <i class="el-icon-back"></i>
          </div>
          <div
            v-show="showRightBtn"
            class="show-menu-btn hidden-left"
            @click="
              isCollapse = false
              showRightBtn = false
            "
          >
            <i class="el-icon-right"></i>
          </div>
        </div>

        <!-- 内容区域 -->
        <div class="report-content">
          <!-- 头部 -->
          <div class="report-content-header">
            <div class="report-l" v-show="opt.nowYear">
              {{ childParams.name }}
            </div>
            <div class="report-r">
              <p @click="downloadBtn" class="report-l cursor">
                下载<i class="el-icon-download"></i>
              </p>
            </div>
          </div>
          <!-- 内容 -->
          <div>
            <Data-download-table
              :loading="loading"
              :childParams="childParams"
              :tableHeight="boxh - headerH - 80"
              @setLoading="setLoading"
              @gotoGis="gotoGis"
            >
            </Data-download-table>
          </div>
        </div>
      </div>
      <!-- 分页 -->
      <!-- <div class="report-footer">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div> -->
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import ReportPageContent from './reportPageContent'
import DataDownloadTable from './dataDownloadTable'
import ReportPageContentDouble from './reportPageContentDouble'
import { getCNTimestamp } from '@/utils/index'

export default {
  name: 'reportPage',
  components: { ReportPageContent, ReportPageContentDouble, DataDownloadTable },
  inject: ['reload'],
  data() {
    return {
      searchIndex: 0,
      totalIndex: 0,
      initOnce: true, //用来控制组件方法只执行一次
      scaleSize: 1.5, //用来做点击 +按钮 做初始化比例
      oldInputSize: 20, //记录旧的inputSize
      fixId: '1', //记录翻页、自输页码的page拼凑值 或者点击列表的id值
      isCollapse: false, //侧边收缩栏是否收缩
      showRightBtn: false,
      showRightBtnTimer: '',
      reportIndex: 1,
      boxh: 0,
      headerH: 0,
      activeIndex: 1,
      activeName: 0,
      timeList: [],
      oneLevelList: [],
      treeData: [],
      getTreeList: [],
      reportId: '',
      positionId: '',
      inputSearch: '',
      emailDialog: false, //邮件弹窗
      emailForm: {
        //发送邮件
        addressee: '',
        theme: '',
        mainText: '',
        sendLoading: false
      },
      opt: {
        //选择时间及标题
        nowYear: null,
        nowMonth: null,
        titleName: null
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      allPage: 0,
      inputPage: 1,
      selectIndex: '',
      inputSize: 30, //纸张缩放大小

      doubleIndex: 0, //双栏当前页

      isShowImg: true, //是否显示头部大图

      leftListWidth: 288,
      isMove: false,
      startX: 0,
      originalX: 288,
      contractionBarWidth: 14,
      showReportTree: true, //展示树形图
      pointonIdTimer: null, //定位id 定时清除计时器
      reloadTimer: null, //重载的计时器 用于滚动到之前位置
      currentPage: 4,
      pageSizes: [50, 100, 200, 300],
      pageSize: 50,
      total: 400,
      childParams: '',
      loading: false,
      treeId: ''
    }
  },
  computed: {
    ...mapState(['home'])
  },
  watch: {
    '$route.path': {
      handler(val) {
        this.reportIndex = this.$route.path == '/home/currentPage' ? 1 : 2
        // console.log(1,'currentPage');
        // this.getMenuList(); 不需要多余的操作
      },
      deep: true
    },
    inputPage: {
      handler(a) {
        if (a > this.allPage) this.inputPage = this.allPage

        // 固定dom节点id
        this.fixId = 'page' + (this.inputPage - 1)
      }
    },
    treeData: function() {
      //dom渲染执行
      this.$nextTick(function() {
        const box = document.getElementById('header_h')
        const H = box ? box.clientHeight + 10 : 0
        this.headerH = H
      })
    }
  },
  created() {
    this.reportIndex = this.$route.path == '/home/currentPage' ? 1 : 2
    this.getH()
    this.getMenuList()
  },
  mounted() {},
  methods: {
    // 跳转到GIS页面
    gotoGis(form) {
      switch (form.routType) {
        case 'user':
          this.$root.form = form
          this.$router.push({
            path: '/gisPage/user'
            // query:{ form }
          })
          break
      }
    },
    setLoading(flag) {
      this.loading = flag
    },
    showRightBtnFun() {
      this.isCollapse = true
      if (this.showRightBtnTimer) {
        clearTimeout(this.showRightBtnTimer)
      }
      this.showRightBtnTimer = setTimeout(() => {
        this.showRightBtn = true
      }, 190)
    },
    changeShowImg() {
      this.isShowImg = false
      this.headerH = 0
    },

    cssText(size, endMarginNum, num) {
      const a = `transform:scale(${size});-ms-transform:scale(${size});-webkit-transform-origin:scale(${size});-moz-transform-origin:scale(${size});-o-transform:scale(${size});`
      const b = `margin-bottom:-${endMarginNum}px;`
      const t = `margin-top:-${(1 - size) * 560}px;`
      const b1 = `margin-bottom:-${(1 - size) * 560}px;`
      return num == 1 ? a + b : a + b1 + t
    },
    // 重载树形图
    reloadTree() {
      // 记录刷新前的 滚动位置
      let scrollTop = this.$refs.reportTree[0].$el.scrollTop
      this.showReportTree = false
      this.$nextTick(vm => {
        this.showReportTree = true
        // 马上调会获取不到 所以加计时器
        if (this.reloadTimer) {
          clearTimeout(this.reloadTimer)
        }
        this.reloadTimer = setTimeout(() => {
          this.$refs.reportTree[0].$el.scrollTop = scrollTop
        }, 20)
      })
    },
    /**
     * 下载报告
     */
    downloadBtn() {
      const { reportId, beanName, mnc, name } = this.childParams
      if (!reportId) {
        return false
      }
      window.open(
        process.env.VUE_APP_API_URL +
          '/caict/downReport/downTableData?reportId=' +
          reportId +
          '&beanName=' +
          beanName +
          '&mnc=' +
          mnc +
          '&name=' +
          name
      )
    },

    /**
     * 切换月份
     */
    changeMonth(item, i) {
      if (this.activeIndex != i) {
        const reports = item['reports']
        this.oneLevelList = reports
        let name = ''
        if (reports && reports.length > 0) {
          this.getReportTitle(reports[0].id)

          // 切换月份 需要切换发送邮件的正文以及标题
          let index = reports[0].fileName.indexOf('.')
          let theme = reports[0].fileName.substring(0, index)
          this.emailForm.theme = theme
          this.emailForm.mainText = theme + '，请查收'

          name = reports[0]['name']
        }
        this.opt = {
          nowYear: item.year,
          nowMonth: item.timestamp,
          titleName: name
        }
        this.activeIndex = i
      }
    },

    /**
     * 获取页面高度
     */
    getH() {
      const box = document.getElementById('app')
      const h = box && box.clientHeight
      this.boxh = h ? h - 60 : 100
    },

    /**
     * 切换 手风琴
     */
    changeCollapse(i) {
      if (i === 0 || i) {
        const item = this.oneLevelList[i]
        this.opt.titleName = item.name
        this.getReportTitle(item['id'])
      }
    },

    /**
     * 获取菜单列表数据 time
     */
    getMenuList() {
      const routeType = this.$route.meta.routeType //1报告页面 2gis页面 3设置页面
      let list = []
      const _this = this
      this.api.getReportListForIndex().then(data => {
        const dataList = data.data
        if (dataList && dataList.length > 0) {
          dataList.sort((a, b) => {
            return b.year * 100 + b.endMonth - (a.year * 100 + a.endMonth)
          })
          dataList.forEach((v, i) => {
            const month =
              String(v.endMonth).length == 1 ? '0' + v.endMonth : v.endMonth
            const reports = v.reports
            const index = list.findIndex(d => {
              return d['timestamp'] == v.year
            })
            // 没有当前年份需加入这个年份
            if (index == -1) {
              list.push({
                year: v.year,
                timestamp: v.year,
                id: null,
                reports: []
              })
            }
            let reportsList = [],
              firstName = null
            if (reports && reports.length > 0) {
              // 当前月份的所有报告
              reports.forEach((d, j) => {
                const name = this.levelOneReport(d.templateType)
                if (i == 0 && j == 0) {
                  // 初始化第一个数据展开 调用接口获取数据
                  this.getReportTitle(d.id)
                  firstName = name
                  const index = d.fileName.indexOf('.')
                  const theme = d.fileName.substring(0, index)
                  this.emailForm.theme = theme
                  this.emailForm.mainText = theme + '，请查收'
                }
                reportsList.push({
                  year: v.year,
                  month: month, //中文月份
                  id: d.id,
                  templateType: d.templateType,
                  name,
                  fileName: d.fileName
                })
              })
            }
            if (i == 0) {
              this.opt = {
                nowYear: v.year,
                nowMonth: month,
                titleName: firstName
              }
            }

            // 当前年份的所有月份
            list.push({
              timestamp: month,
              cnTimestamp: getCNTimestamp(month), //中文数字
              id: 'id', //用于判断是年份还是月份 假的
              reports: reportsList,
              year: v.year
            })
          })
        }
        _this.timeList = list
        if (list && list.length > 0) {
          const a = list[_this.activeIndex]['reports']
          _this.oneLevelList = a
        }
      })
    },

    /**
     * 获取一级报告名称
     */
    levelOneReport(templateType) {
      let indexName = ''
      switch (templateType) {
        case 1:
          indexName = '第一册 综合报告'
          break
        case 2:
          indexName = '第三册 网络报告'
          break
        case 3:
          indexName = '第二册 市场报告'
          break
        case 4:
          indexName = '第四册 重点场景报告'
          break
        default:
      }
      return indexName
    },

    /**
     * 获取导航标题 内容 获取目录数据
     */
    getReportTitle(id, i = 0) {
      this.treeData = []
      this.reportId = id
      this.api
        .getReportTableListByReportId({
          reportId: id
        })
        .then(data => {
          this.treeData = data.data
          this.getCurrentParams([data.data[0]])
        })
    },

    getCurrentParams(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].detailType == 11) {
          this.setParams(data[i])
        } else {
          this.getCurrentParams([data[i].children[0]])
        }
      }
    },

    /**
     * 树形节点点击
     */
    handleNodeClick(val) {
      if (val.detailType == 11) {
        this.loading = true
        this.setParams(val)
      } else {
        this.$refs.reportTree[0].setCurrentKey(this.treeId)
      }
    },

    // 修改参数
    setParams(val) {
      this.inputPage = val.page
      // 固定dom节点id
      this.fixId = val.id
      this.positionId = val.id
      this.treeId = val.id
      this.setDoubleIndex(val.page)
      this.childParams = {
        reportId: this.reportId,
        beanName: val.beanName,
        mnc: val.mnc,
        name: val.name,
        titleList: JSON.stringify(val.titleList)
      }
    },

    setDoubleIndex(a) {
      this.doubleIndex = (a % 2 == 0 ? a / 2 : (a + 1) / 2) - 1
      // pointonId 置空 用于修复下次跳转到同节点不跳的问题
      if (this.pointonIdTimer) {
        clearTimeout(this.pointonIdTimer)
      }
      // reload 用于清除 选中缓存
      this.reloadTree()
      this.pointonIdTimer = setTimeout(() => {
        this.$refs.reportTree[0].setCurrentKey(this.positionId)
        this.positionId = null
      }, 50)
    },

    /**
     * 拖拽改变宽度
     */
    mouseDownSc(e) {
      e.stopPropagation()
      e.preventDefault()
      this.loading = false
      const scale = document.getElementById('scale')
      let w1 = box.offsetWidth
      let x1 = e.clientX
      let width = null

      this.isMove = true
      this.startX = e.clientX
      this.originalX = scale.offsetLeft
      this.contractionBarWidth = 50

      document.onmousemove = ev => {
        //用鼠标的位置减去鼠标初始位置，得到拖动的距离
        let left = ev.clientX - x1
        left = parseInt(left)
        width = w1 + left
        this.leftListWidth = width
      }

      document.onmouseup = e => {
        if (width !== null) {
          this.leftListWidth = parseInt(width)
        }
        this.contractionBarWidth = 14
        this.isMove = false

        document.onmousemove = null
        document.onmouseup = null
      }
      return false
    },
    // 修改当前页有多少条
    handleSizeChange(e) {
      // window.console.log(e)
    },
    // 切换页码
    handleCurrentChange(e) {
      // window.console.log(e)
    },
    append(node, data) {
      // window.console.log(node,data,'wdata')
    }
  }
}
</script>
<style lang="scss" scoped>
.report-box {
  width: 100%;
  flex-direction: column;
  .icon-view-style {
    color: #0297ff;
    margin-right: 5px;
  }
  .time-box {
    background: #fafafa;
    width: 93px;
    padding: 10px;

    .year-style {
      font-family: Source Han Sans CN;
      color: #0297ff;
      font-size: 16px;
    }
    .month-style {
      font-family: Source Han Sans CN;
      color: #0e2345;
      font-size: 12px;
      cursor: pointer;
    }
    .active {
      width: 36px;
      height: 20px;
      background: #0297ff;
      border-radius: 10px;
      display: inline-block;
    }
  }

  .report-list-box {
    background: #fff;
    border-right: 1px solid #ced3e0;
    display: flex;
    position: relative;

    .report-list {
      flex-grow: 1;
      width: 288px;
      overflow: hidden;
      transition: all 0.2s ease-out;

      .report-tit {
        padding: 0 15px;
        color: #666;
        font-size: 14px;
        height: 40px !important;
        white-space: nowrap;
        background: #fafafa;
      }

      // 手风情报告标题
      .report-collapse-tit {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-right: 20px;
        > span > i {
          font-size: 16px;
          margin-left: 10px;
        }
      }
    }
    .contraction-bar {
      height: 100%;
      cursor: ew-resize;
      position: absolute;
      top: 0;
      z-index: 1;
    }

    // 灰块
    .grey-box {
      position: fixed;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      z-index: 1;
    }

    // 侧边收缩栏
    .show-menu-btn {
      cursor: pointer;
      position: absolute;
      top: 50%;
      z-index: 3;
      text-align: center;
      background: #99a2b1;
      height: 48px;
      line-height: 48px;
      width: 24px;
      color: #fff;
    }
    .hidden-left {
      border-radius: 0 8px 8px 0;
      left: 0;
    }
    .show-left {
      border-radius: 8px 0 0 8px;
      right: 0;
    }
  }

  .report-content {
    background: #fff;
    flex-grow: 1;
    .report-content-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 20px;
      height: 35px;
      background: #fafafa;
      box-shadow: 0px 2px 1px 0px rgba(153, 153, 153, 0.19);

      .report-l {
        color: #0297ff;
        font-size: 14px;
        font-family: Source Han Sans CN;
      }
      .cursor {
        cursor: pointer;
      }
      .report-r {
        display: flex;
        align-items: center;

        .el-icon-message {
          font-size: 20px;
        }
        .send-btn {
          display: flex;
          align-items: center;
        }
      }
    }

    .down-load {
      width: 50px;
      height: 50px;
      display: flex;
      justify-content: center;
      align-items: center;
      position: fixed;
      bottom: 55px;
      right: 15px;
      background: #0096ff;
      cursor: pointer;
      border-radius: 100%;
      z-index: 10;
    }
  }
}
.flex {
  display: flex;
  flex-grow: 1;
}
.report-footer {
  height: 30px;
  line-height: 30px;
  display: flex;
  justify-content: space-between;
  padding: 0 10px;
  background: #f4f6f9;
  .el-pagination {
    text-align: right;
    width: 100%;
    .el-pagination__jump {
      .el-input__inner {
        background: transparent;
      }
    }
  }
  .footer-text {
    color: #0e2345;
    font-size: 12px;
  }
  .report-page {
    display: flex;
    align-items: center;
    .total-page {
      margin: 0 10px 0 5px;
      color: #41485d;
    }
  }
  .slider-box {
    width: 226px;
    display: flex;
    align-items: center;
  }
}
.header-top-box {
  margin-bottom: 10px;
  position: relative;
  img {
    width: 100%;
    height: auto;
  }
  i {
    position: absolute;
    right: 20px;
    top: 10px;
    font-size: 24px;
    color: #fff;
    cursor: pointer;
  }
}
</style>
